import pandas
from tkinter import messagebox
from Model import *
from View import *


class MatchController:
    def __init__(self):
        self.state = False

    def _readexcel2(self):
        if len(excel2MatchChooser.filenames) > 0 :
            return excel2MatchChooser.selected()[excel2MatchChooser.filenames[0]]
        else:
            return "None"
        pass

    def _showinputError(self):
        if RF.wspointer !='主菜单':
            messagebox.showinfo("文件地址无效",
                                "请选择需要处理的EXCEL文件！")
            matchMenu.ws.focus_force()
            print("录入地址无效！")

    def getexcel2(self):
        excel2MatchChooser.choose()
        print(self._readexcel2())
        if self._readexcel2() != "None":
            excel2.inputexcel(self._readexcel2())
            excelMatchResult.createexcel(df = excel0.df)
            matchPreviewTable.loaddata(excelMatchResult.df)
        else:
            self._showinputError()

    def _match(self):
        excelMatchResult.createexcel(df=excel0.df)
        cindex = matchIndexChooser.getvalue()
        print(f"从表2对比数据以{cindex}为索引")
        result = excelMatchResult.compareexcel(excel2, cindex)
        return result

    def preview(self):
        state = self._match()
        if state:
            if len(excelMatchResult.df.index) == 0:
                messagebox.showinfo(title='没有缺失数据', message="没有找到缺失的数据，对比结果为空！")
                matchPreviewTable.focus_force()
            matchPreviewTable.loaddata(excelMatchResult.df)
            matchPreviewWindow.open()
        else:
            print("对比失败！请重新选择索引列")
            messagebox.showinfo(title='操作失败', message="对比失败！请重新选择索引列")
            matchMenu.ws.focus_force()

    def save(self):
        state = self._match()
        if state:
            if len(excelMatchResult.df.index) == 0:
                messagebox.showinfo(title='没有缺失数据', message="没有找到缺失的数据，对比结果为空！")
                matchMenu.ws.focus_force()
            if excel0.ftype == 'xlsx':
                name = '缺失数据_' + excel0.fname[:] + '.xlsx'
            else:
                name = '缺失数据_' + excel0.fname[:].rpartition('.')[0] + '.xlsx'
            ExcelSaver.setinitialfile(name)
            try:
                path = ExcelSaver.save()[1]
                print(excelMatchResult.df)
                excelMatchResult.saveexcel(path)
                messagebox.showinfo("保存提示","保存成功！")
                matchMenu.ws.focus_force()
            except:
                messagebox.showinfo("地址无效警告",
                                    "请重新选择保存位置，并填写正确的文件后缀名")
                matchMenu.focus_force()

        else:
            print("对比失败！请重新选择索引列")
            messagebox.showinfo(title='操作失败', message="对比失败！请重新选择索引列")
            matchMenu.ws.focus_force()


matchController = MatchController()
excel2MatchChooser.resetcommand(command=matchController.getexcel2)
matchPreviewButton.configure(command=matchController.preview)
matchSaveButton.configure(command=matchController.save)